<template>
  <!--  <el-collapse v-model="activeCollapse" class="permission-collapse">-->
  <!--    <el-collapse-item v-for="(menu, index) in data" :key="menu.id" :name="menu.id">-->
  <!--      <template slot="title">-->
  <!--        <el-checkbox :indeterminate="isIndeterminate[index]" v-model="checkAll[index]" @change="handleCheckAllChange($event, index, menu)">{{ menu.menuName }}</el-checkbox>-->
  <!--      </template>-->
  <!--      <template v-if="menu.menuList">-->
  <!--        <PermissionItem v-for="(child, curIndex) in menu.menuList" :key="child.id" :data="child" :checked="checkeditems" @change="permissionChange($event, curIndex, index, menu)"/>-->
  <!--      </template>-->
  <!--    </el-collapse-item>-->
  <!--  </el-collapse>-->
  <div>
    <el-checkbox
      :indeterminate="isIndeterminate"
      v-model="checkAll"
      @change="handleCheckAllChange"
      style="margin-bottom: 10px"
      >{{ $t("system.role.all") }}</el-checkbox
    >
    <!-- <el-button size="mini" @click="setDept">可管理部门设置</el-button> -->
    <slot name="topmenu"></slot>
    <PermissionCollapse
      ref="collapse"
      :parent="provideParent"
      :data="data"
      :defaultCheckedItems="defaultCheckedItems"
      :defaultCheckedMenus="defaultCheckedMenus"
      @checkedChange="checkChange"
      @manageraiapp="manageraiapp"
      @setdept="setDept"
      @setDS="setDSData"
      @setproject="setproject"
    />
    <HuilanDialog
      :title="$t('system.role.departmentSet')"
      append-to-body
      :visible.sync="deptDialogVisible"
      width="900px"
    >
      <!--      <avue-form ref="deptForm" v-model="form" :option="option" ></avue-form>-->
      <TreeSelect
        v-if="deptDialogVisible"
        multiple
        v-model="deptIds"
        :showValue="deptNames"
        :treeOption="treeOption"
      />

      <template v-slot:footer>
        <el-button size="small" type="primary" @click="saveDepts">{{
          $t("aicosCommon.confirmBtn")
        }}</el-button>
        <el-button size="small" @click="deptDialogVisible = false">{{
          $t("aicosCommon.cancelBtn")
        }}</el-button>
      </template>
    </HuilanDialog>
    <HuilanDialog
      :title="$t('system.role.largeScreenSet')"
      append-to-body
      :visible.sync="projectDialogVisible"
      width="600px"
    >
      <template v-if="projectDialogVisible">
        <el-select
          v-model="categoryName"
          :placeholder="$t('aicosCommon.pleaseSelect')"
          size="small"
          multiple
          style="width: 100%"
        >
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.categoryName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </template>
      <template v-slot:footer>
        <el-button size="small" type="primary" @click="saveProject">{{
          $t("aicosCommon.confirmBtn")
        }}</el-button>
        <el-button size="small" @click="projectDialogVisible = false">{{
          $t("aicosCommon.cancelBtn")
        }}</el-button>
      </template>
    </HuilanDialog>
    <HuilanDialog
      title="可管理数据集"
      append-to-body
      :visible.sync="DSDialogVisible"
      width="900px"
    >
      <DStree
        v-if="DSDialogVisible"
        multiple
        v-model="DSIds"
        :showValue="DSNames"
        :treeOption="DSTreeOption"
      />
      <template v-slot:footer>
        <el-button size="small" type="primary" @click="saveDS">{{
          $t("aicosCommon.confirmBtn")
        }}</el-button>
        <el-button size="small" @click="DSDialogVisible = false">{{
          $t("aicosCommon.cancelBtn")
        }}</el-button>
      </template>
    </HuilanDialog>
  </div>
</template>

<script>
import { getDeptLazyTree } from "@/api/system/dept";
import {
  getDeptByRoleId,
  saveRoleDeptRelation,
  categoryList,
  saveCategory,
  getDSTree,
  saveRoleReportRelation,
  getReportByRoleId,
  getCanManagerReportByAccount,
  getIdByTreeData,
} from "@/api/system/role";
import PermissionCollapse from "./permissionCollapse";
import TreeSelect from "@/components/TreeSelect";
import DStree from "@/components/TreeSelect/DStree";
import { mapGetters } from "vuex";
export default {
  components: {
    // PermissionItem,
    PermissionCollapse,
    TreeSelect,
    DStree,
  },
  props: {
    className: {
      type: String,
      default: "",
    },
    data: {
      type: Array,
      default() {
        return [];
      },
    },
    defaultCheckedItems: {
      type: Array,
      default() {
        return [];
      },
    },
    defaultCheckedMenus: {
      type: Array,
      default() {
        return [];
      },
    },
    role: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    // const me = this;
    return {
      checkAll: false,
      isIndeterminate: false,
      deptDialogVisible: false,
      //
      projectDialogVisible: false,
      options: [],
      categoryName: [],
      //
      selectedDepts: [],
      deptIds: [],
      deptNames: [],
      treeOption: {
        defaultExpandedKeys: ["0"],
        // showCheckbox: true,
        // checkStrictly: true,
        props: {
          label: "deptName",
          isLeaf: "leaf",
          // value: 'id'
        },
        lazy: true,
        key: "id",
        // expandOnClickNode: false,
        load: function (node, resolve) {
          let parentId = node.data && node.data.id;
          if (node.level === 0) {
            // parentId = 0
            resolve([{ deptName: "部门目录", id: "0", disabled: true }]);
            return;
          }
          // const parentId = node.data.id;
          getDeptLazyTree(parentId).then((res) => {
            const data = res.data.data;
            // setTimeout(()=>{
            resolve(
              data.map((item) => {
                return {
                  ...item,
                  leaf: item.isLeaf === "1",
                };
              })
            );
            // }, 5000)
          });
        },
      },
      // 可管理数据集
      selectedDS: [],
      DSDialogVisible: false,
      DSIds: [],
      DSNames: [],
      DSTreeOption: {
        defaultExpandedKeys: ["0"],
        // showCheckbox: true,
        // checkStrictly: true,
        props: {
          label: "name",
          isLeaf: "leaf",
          value: "id",
        },
        lazy: false,
        key: "id",
        data: [],
      },
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  methods: {
    provideParent() {
      return this;
    },
    handleCheckAllChange(val) {
      this.isIndeterminate = false;
      this.checkAll = val;
      this.$emit("checkedAllChildren", val);
    },
    checkChange(data) {
      this.checkAll = data.checked;
      this.isIndeterminate = data.isIndeterminate;
    },
    getSubmitData() {
      const { menuIds, resourceIds } = this.$refs.collapse.getCheckedMenus();
      return {
        menuIds: menuIds.join(),
        resourceIds: resourceIds.join(),
      };
    },
    async setproject() {
      let res = await categoryList(this.role.id);
      if (res.data.success) {
        this.options = res.data.data.list;
        this.categoryName = res.data.data.key;
      }
      this.projectDialogVisible = true;
    },
    async saveProject() {
      let obj = { roleId: this.role.id, categoryIds: this.categoryName };
      await saveCategory(obj);
      this.$message.success(this.$t("aicosCommon.saveSuccessTip"));
      this.projectDialogVisible = false;
    },
    async setDept() {
      await this.getSelectedDept();
      this.deptDialogVisible = true;
    },
    manageraiapp() {
      this.$emit("manageraiapp");
    },
    async saveDepts() {
      const data = {
        roleId: this.role.id,
        list: this.deptIds.map((item) => ({ id: item })),
      };
      await saveRoleDeptRelation(data);
      this.$message.success(this.$t("aicosCommon.saveSuccessTip"));
      this.deptDialogVisible = false;
    },
    async getSelectedDept() {
      const {
        data: { data },
      } = await getDeptByRoleId(this.role.id);
      let ids = [];
      let names = [];
      data.forEach(({ id, deptName }) => {
        ids.push(id);
        if (id == "0") {
          names.push("部门管理");
        } else {
          names.push(deptName);
        }
      });
      this.deptIds = ids;
      this.deptNames = names;
      this.selectedDepts = data;
    },
    traverseTree(node, ids = []) {
      if (node) {
        node.forEach((item) => {
          let flag = false;
          if (!item.leaf) {
            flag = true;
          }
          if (
            this.userInfo.isAdmin === "0" &&
            item.leaf &&
            !ids.includes(item.id)
          ) {
            flag = true;
          }
          if (flag) {
            item.disabled = true;
          } else {
            item.disabled = false;
          }
          this.traverseTree(item.children, ids);
        });
      }
    },

    flattenTree(tree, parentId = null) {
      return tree.reduce((flattened, node) => {
        const flatNode = { ...node, parentId };
        flattened.push(flatNode);
        if (node.children && node.children.length) {
          flattened.push(...this.flattenTree(node.children, node.id));
        }
        return flattened;
      }, []);
    },
    async setDSData() {
      getDSTree().then((res) => {
        let treeData = res.data.data[0].children;
        if (this.userInfo.isAdmin === "0") {
          getCanManagerReportByAccount().then((res) => {
            let ids = res.data.data;
            this.DSTreeOption.data = [
              {
                name: "数据集管理",
                id: "0",
                disabled: true,
                children: treeData,
              },
            ];
            this.traverseTree(this.DSTreeOption.data, ids);
          });
        } else {
          this.DSTreeOption.data = [
            {
              name: "数据集管理",
              id: "0",
              disabled: true,
              children: treeData,
            },
          ];
        }
        this.traverseTree(this.DSTreeOption.data);
      });
      await this.getSelectedDS();
      this.DSDialogVisible = true;
    },
    async saveDS() {
      const data = {
        roleId: this.role.id,
        list: this.DSIds,
      };
      await saveRoleReportRelation(data);
      this.$message.success(this.$t("aicosCommon.saveSuccessTip"));
      this.DSDialogVisible = false;
    },
    async getSelectedDS() {
      const {
        data: { data },
      } = await getReportByRoleId(this.role.id);
      let ids = [];
      let names = [];
      data.forEach((id) => {
        getIdByTreeData(id).then((res) => {
          if (id == "0") {
            names.push("数据集管理");
          } else {
            names.push(res.data.name);
          }
          ids.push(id);
        });
      });
      this.DSIds = ids;
      this.DSNames = names;
      this.selectedDS = data;
    },
  },
};
</script>

<style lang="scss" scoped>
.permission-collapse {
  /deep/ .el-collapse-item__content {
    padding-bottom: 0;
  }
}
</style>
